<?php

namespace App\Http\Model;

use Illuminate\Database\Eloquent\Model;

class RedEnvelopeLog extends Model {
    protected $table = 'red_envelope_log';
    public static function insert(int $from, int $to, int $count, float $rate, int $fee) : ?string {
        $no = makeUuid(32);
        $ok = self::query()->insert([
            'no'    => $no,
            'from'  => $from,
            'to'    => $to,
            'count' => $count,
            'rate'  => $rate,
            'fee'   => $fee,
        ]);
        return $ok?$no:null;
    }

    public static function sendRecord(int $userId, int $page_num, int $page_size) : array{
        $selfTable = "red_envelope_log";
        $userTable = 'user';
        $result = self::query()
            ->select([$selfTable . '.to as user_id', $selfTable . '.count',  $selfTable . '.fee',$selfTable . '.created_at',
                $userTable . '.uuid', $userTable . '.nickname', $userTable . '.portrait'])
            ->where($selfTable . '.from', $userId)
            ->leftJoin($userTable,$selfTable . '.to', '=',  $userTable . '.user_id')
            ->orderBy($selfTable . '.created_at', 'desc')
            ->offset($page_num * $page_size)
            ->limit($page_size)
            ->get()
            ->all();
        foreach ($result as &$record) {
            $portrait = $record->portrait;
            $portrait = json_decode($portrait,true);
            $portrait = $portrait[0]??'';
            $record->portrait = build_image($portrait);
        }

        return $result;
    }
}